<!--
	地震灾害现场调查与烈度评估
	Created by Penglei on 2023/08/08
-->
<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header to="/lossAssessment" :back="true" />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <subheadings name="地震烈度图" />
          <SeismicIntensity />
        </div>
        <div class="app-left-item" style="">
          <subheadings name="现场数据占比" />
          <OnSiteProportion v-if="isShowData" :datas="XcProportion" />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline name="地震烈度评定结果及调查数据" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '-30px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <OlMap :refId="'intensityassessment'" :showSouthSea="!showTianditu" :blueChina="!showTianditu" :showTianditu="showTianditu" style="height: 100%"
                 @getMap="getMap" @mapClick="mapClick"></OlMap>
          <div ref="popupElement" class="popup-bg" id="map-popup">
            <div class="triangle"></div>
            <div class="popup-head">
              <div class="popup-head-title">XXX县历年来地震灾损情况表</div>
              <div class="popup-head-x">X</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <subheadings name="典型破坏照片" />
          <TypicalDamagePhotos
            :imgSixList="imgSixList"
            :imgSevenList="imgSevenList"
            :imgEightList="imgEightList"
            :imgNineList="imgNineList"
            :imgTenList="imgTenList"
          />
        </div>
        <div class="app-right-item">
          <subheadings name="地震灾害损失评估访问统计" />
          <AccessStatistics v-if="isShow" :listData="SystemAchievementsStatistics" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="IntensityAssessment">
// 地震烈度图
import SeismicIntensity from './components/SeismicIntensity';
// 现场数据占比
import OnSiteProportion from './components/OnSiteProportion';
// 地震烈度图
import TypicalDamagePhotos from './components/TypicalDamagePhotos';
// 访问统计
import AccessStatistics from './components/AccessStatistics';
// 系统选择
import SystemSelect from '@/components/SystemSelect';
import { getXcProportion, getVisitNum, getSecondMapDate, getDisasterImage } from '@/api/lossAssessment.js';
// start
// import OlMap from '@/components/Olmap';
import OlMap from '@/components/OlMap/index';
import WKT from 'ol/format/WKT';
import { extend } from 'ol/extent';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon, Text } from 'ol/style';
import Feature from 'ol/Feature';
import { Point } from 'ol/geom';
import Circle from 'ol/geom/Circle';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import Overlay from 'ol/Overlay';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { getChinaBaseMap } from '@/map/projMap.js';
import { convertToGeoJSON } from '@/utils/map.js';
import { onMounted } from 'vue';
// 现场数据占比
const XcProportion = ref({});
// 地震灾害损失评估访问统计
const SystemAchievementsStatistics = ref([]);
const isShow = ref(false);
const isShowData = ref(false);
const intensityId = ref(null);
const intensityLevel = ref(null);
const mapInstance = ref(null);
const vectorLayer = ref(null);
const mapPopupLayer = ref(null);
const intensityFeatures = ref(null);
const popupElement = ref();
const imgSixList = ref([]);
const imgSevenList = ref([]);
const imgEightList = ref([]);
const imgNineList = ref([]);
const imgTenList = ref([]);
const showTianditu = ref(true);

let timer;
// 初始化索引
var currentIndex = 0;
getData();
function getData() {
  getXcProportion({ iaId: 2 }).then((res) => {
    XcProportion.value = res.data;
    isShowData.value = true;
  });

  // 地震灾害损失评估访问统计
  getVisitNum({ system: 0, num: 5 }).then((res) => {
    SystemAchievementsStatistics.value = res.data;
    isShow.value = true;
  });
}
function imgShow() {
  if (intensityLevel.value == 6) {
    getDisasterImage({ intensity: intensityLevel.value }).then((res) => {
      imgSixList.value = res.data;
      imgSixList.value.map((item) => {
        item.url = import.meta.env.VITE_APP_BASE_API + '/attachment/downLoadByUrl?url=' + encodeURIComponent(item.url);
      });
    });
  }
  if (intensityLevel.value == 7) {
    getDisasterImage({ intensity: intensityLevel.value }).then((res) => {
      imgSevenList.value = res.data;
      imgSevenList.value.map((item) => {
        item.url = import.meta.env.VITE_APP_BASE_API + '/attachment/downLoadByUrl?url=' + encodeURIComponent(item.url);
      });
    });
  }
  if (intensityLevel.value == 8) {
    getDisasterImage({ intensity: intensityLevel.value }).then((res) => {
      imgEightList.value = res.data;
      imgEightList.value.map((item) => {
        item.url = import.meta.env.VITE_APP_BASE_API + '/attachment/downLoadByUrl?url=' + encodeURIComponent(item.url);
      });
    });
  }
  if (intensityLevel.value == 9) {
    getDisasterImage({ intensity: intensityLevel.value }).then((res) => {
      imgNineList.value = res.data;
      imgNineList.value.map((item) => {
        item.url = import.meta.env.VITE_APP_BASE_API + '/attachment/downLoadByUrl?url=' + encodeURIComponent(item.url);
      });
    });
  }
  if (intensityLevel.value == 10) {
    getDisasterImage({ intensity: intensityLevel.value }).then((res) => {
      imgTenList.value = res.data;
      imgTenList.value.map((item) => {
        item.url = import.meta.env.VITE_APP_BASE_API + '/attachment/downLoadByUrl?url=' + encodeURIComponent(item.url);
      });
    });
  }
}

// start
const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);

  // addProvinceNameLayer();

  createVectorLayer();
  getMapData();
  createPopUpLayer();
};

const getMapData = () => {
  getSecondMapDate().then((res) => {
    console.log('res---', res);
    if (res.code == 200) {
      let data = res.data;
      let features = [];
      data.resultDates.forEach((item) => {
        let featureTmp = new WKT().readFeature(item.geom);
        featureTmp.set('id', item.id);
        featureTmp.set('intensity', item.intensity);
        featureTmp.set('type', 2);
        featureTmp.setStyle(polygonStyle(featureTmp));
        features.push(featureTmp);
      });
      intensityFeatures.value = features;
      addPolygonLayer(intensityFeatures.value);
      //
      // let geojson = convertToGeoJSON(data.resultDates);
      // const geojsonFormat = new GeoJSonFormat();
      // intensityFeatures.value = geojsonFormat.readFeatures(geojson);
      // console.log('features---', intensityFeatures.value);
      // addPolygonLayer(intensityFeatures.value);
    }
  });
};
const polygonStyle = (feature) => {
  return new Style({
    fill: new Fill({
      color: getColorByIntensity(feature.get('intensity')),
    }),
    // stroke: new Stroke({
    //   color: 'red',
    //   width: 1,
    // }),
  });
};
const blinkingStyle = (feature) => {
  return new Style({
    fill: new Fill({
      color: getColorByIntensity(feature.get('intensity')),
    }),
    stroke: new Stroke({
      color: 'red',
      width: 3,
    }),
  });
};
function getColorByIntensity(intensity) {
  let color = {
    // 6: 'rgba(255, 37, 37, 0.4)',
    // 7: 'rgba(255, 37, 37, 0.5)',
    // 8: 'rgba(255, 37, 37, 0.6)',
    // 9: 'rgba(255, 37, 37, 0.7)',
    // 10: 'rgba(255, 37, 37, 0.8)',
    6: 'rgba(255,190,190,0.7)',
    7: 'rgba(255,127,127,0.7)',
    8: 'rgba(200,40,40,0.7)',
    9: 'rgba(168,0,0,0.7)',
    10: 'rgba(140,0,0,0.7)',
  };
  return color[intensity];
}
const addPolygonLayer = (features) => {
  vectorLayer.value.getSource().addFeatures(features);
  zoomToMaxExtent(features, 3000);
  setTimer();
};
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
  if (blinkTimer) {
    clearInterval(blinkTimer);
  }
});
let blinkTimer = null;
const setTimer = () => {
  timer = setInterval(() => {
    let feature = intensityFeatures.value[currentIndex];
    if (blinkTimer) {
      clearInterval(blinkTimer);
    }
    blinkTimer = blinkFeature(feature, 1000);
    if (currentIndex === 0) {
      normalFeature(intensityFeatures.value[intensityFeatures.value.length - 1]);
    } else {
      normalFeature(intensityFeatures.value[currentIndex - 1]);
    }
    intensityLevel.value = feature.get('intensity');
    intensityId.value = feature.get('id');
    // console.log('轮询---', intensityLevel.value, intensityId.value);
    imgShow();
    // 增加索引，以处理下一个要素
    currentIndex++;
    // 如果已经处理完所有要素，则重新开始
    if (currentIndex >= intensityFeatures.value.length) {
      currentIndex = 0;
    }
  }, 5000);
};
function zoomToMaxExtent(features, duration) {
  var maxExtent = null;

  for (var i = 0; i < features.length; i++) {
    var feature = features[i];
    var featureGeometry = feature.getGeometry();
    var featureExtent = featureGeometry.getExtent();

    if (maxExtent === null) {
      maxExtent = featureExtent;
    } else {
      maxExtent = extend(maxExtent, featureExtent);
    }
  }
  if (maxExtent !== null) {
    mapInstance.value.getView().fit(maxExtent, { padding: [100, 100, 100, 100], duration: duration });
  }
}
function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 3,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
        // 将闪烁的 CSS 类添加到要素
        className: 'blinking',
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}
const blinkFeature = (feature, blinkInterval) => {
  // 添加要素到图层，并应用闪烁样式
  feature.setStyle(blinkingStyle(feature));
  // 定义闪烁定时器
  var isBlinking = true;
  var blinkTimer = setInterval(function () {
    if (isBlinking) {
      // 移除样式以停止闪烁
      feature.setStyle(polygonStyle(feature));
    } else {
      // 重新应用样式以继续闪烁
      feature.setStyle(blinkingStyle);
    }
    isBlinking = !isBlinking;
  }, blinkInterval);

  // 返回定时器引用，以便稍后停止闪烁
  return blinkTimer;
};
const normalFeature = (feature) => {
  feature.setStyle(polygonStyle(feature));
};
const mapClick = (event) => {
  const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
  return;
  if (features.length > 0) {
    const selectedFeature = features[0];
    // 获取要素的坐标信息
    popupElement.value.style.display = 'block';
    /**
    const coordinate = selectedFeature.getGeometry().getCoordinates();
    mapPopupLayer.value.setPosition(coordinate);
    // 获取地图容器的尺寸和点击事件的位置
    const mapContainerRect = mapInstance.value.getTarget().getBoundingClientRect();
    const clickX = event.pixel[0];
    const clickY = event.pixel[1];

    // 获取弹出框的尺寸
    const popupWidth = popupElement.value.offsetWidth;
    const popupHeight = popupElement.value.offsetHeight;

    // 默认的 positioning
    let positioning = 'top-left';

    // 判断弹出框是否超出地图容器的各个边界
    if (clickX + popupWidth > mapContainerRect.width) {
      positioning = 'top-right';
    } else if (clickX - popupWidth < 0) {
      positioning = 'top-left';
    }

    if (clickY + popupHeight > mapContainerRect.height) {
      positioning = positioning.replace('top', 'bottom');
    } else if (clickY - popupHeight < 0) {
      positioning = positioning.replace('bottom', 'top');
    }

    // 设置弹出框的位置和定位方式
    mapPopupLayer.value.setPositioning(positioning);
     */
    let coordinate = mapInstance.value.getEventCoordinate(event.originalEvent);
    // 设置弹出框的位置
    mapPopupLayer.value.setPosition(coordinate);
    // 在这里添加处理点击事件的逻辑
    console.log('点击了要素：', selectedFeature.getProperties());
  } else {
    mapPopupLayer.value.setPosition(undefined);
  }
};
const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const createPopUpLayer = () => {
  let popup = document.getElementById('map-popup');
  mapPopupLayer.value = new Overlay({
    element: popup,
    positioning: 'center-left',
    offset: [10, 0], // 偏移量，可根据需要进行调整
  });
  mapInstance.value.addOverlay(mapPopupLayer.value);
};
// end
</script>

<style scoped lang="scss">
.app-container {
  min-height: 1080px;
}

.app-map {
  width: 960px;
  height: 100%;
  background-size: 100% 100%;
  overflow: visible;
}

// 左侧
.app-left-item:nth-child(1) {
  height: 455px;
  z-index: 1000;
}

.app-left-item:nth-child(2) {
  height: 465px;
}

// 右侧
.app-right-item:nth-child(1) {
  height: 500px;
}

.app-right-item:nth-child(2) {
  height: 420px;
}

/* start */
.popup-bg {
  min-width: 400px;
  height: 275px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  padding: 17px 15px;
  flex-direction: column;
  position: relative;
  .triangle {
    position: absolute;
    top: 50%;
    left: -10px;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0190f9;
  }
  .popup-head {
    justify-content: center;

    display: flex;
    flex-direction: row;
    font-size: 18px;
    font-family: Source Han Sans CN-Bold, Source Han Sans CN;
    font-weight: bold;
    color: #ffffff;
    line-height: 23px;
    .popup-head-title {
      margin-left: auto;
    }
    .popup-head-x {
      margin-left: auto;
      width: 12px;
      height: 12px;
      color: #e6f4fd;
      opacity: 1;
    }
  }
  .popup-content {
    height: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #e6f4fd;
    line-height: 23px;
    .popup-content-title {
      background: #050426;
      border-radius: 0px 0px 0px 0px;
      opacity: 0.5;
      padding: 10px 34px;
      justify-content: space-between;
      display: flex;
      flex-direction: row;
    }
    .popup-table {
      width: 100%;
      height: 100%;
      margin-right: 20px;
      .el-table {
        width: 90%;
        max-height: 150px;
        overflow-x: hidden;
        overflow-y: auto;
        z-index: 99;
        position: absolute;
        background: rgba(0, 0, 0, 0);
        :deep(tr:hover > td) {
          background: rgba(71, 90, 219, 0.05) !important;
        }
        :deep(.el-table__header) {
          background: rgba(5, 4, 38, 0.4);
          tr {
            background-color: transparent !important;
          }
          th.el-table__cell {
            background-color: transparent !important;
          }
          th.el-table__cell.is-leaf {
            border-bottom: none;
          }
        }

        :deep(.el-table__row) {
          background: rgba(5, 4, 38, 0.4);
        }
        :deep(.el-table__inner-wrapper)::before {
          display: none;
        }
      }
    }
  }
}
/* .popup-bg::before {
  content: '';
  width: 0;
  height: 0;
  border: 15px solid;
  position: absolute;
  top: 50%;
  left: -43px;
  margin-top: -15px;
  border-color: transparent #0190f9 transparent transparent;
}
.popup-bg:after {
  content: '';
  width: 0;
  height: 0;
  border: 15px solid;
  position: absolute;
  top: 50%;
  left: -40px;
  margin-top: -15px;
  border-color: transparent rgba(6, 40, 150, 0.8) transparent transparent;
} */
:deep(.ol-overlaycontainer-stopevent) {
  z-index: 2;
}
/* end */
</style>
